package de.gratnik.chat;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

import android.app.Activity;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.widget.TextView;

public class WiFiChatActivity extends Activity {
	/** Called when the activity is first created. */

	TextView ip = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ip = (TextView) findViewById(R.id.ip);

		try {
			InetAddress addr = getLocalAddress();
			if (addr != null) {
				ip.setText(getIP());
			}
		} catch (IOException e) {

			e.printStackTrace();
		}

	}
	
	private String bytesToIPString(byte[] addr) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < addr.length; ++i) {
			sb.append(addr[i] + "-");
		}
		return sb.toString();
	}

	private InetAddress getLocalAddress() throws IOException {

		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				Log.i("int", intf.getName());
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					Log.i("addr", bytesToIPString(inetAddress.getAddress()));
					if (!inetAddress.isLoopbackAddress()) {
						// return inetAddress.getHostAddress().toString();
						return inetAddress;
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("er", ex.toString());
		}
		return null;
	}
	
	private String getIP() {
		WifiManager wim= (WifiManager) getSystemService(WIFI_SERVICE)  ;

		List<WifiConfiguration> l=  wim.getConfiguredNetworks(); 
		    WifiConfiguration wc=l.get(0); 

		   return Formatter.formatIpAddress(wim.getConnectionInfo().getIpAddress());
	}

}